package com.find.memories.sms;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.find.memories.BaseFragment;
import com.find.memories.MainActivity;
import com.find.memories.R;

public class FragmentSMS extends BaseFragment {

    private ListView mListView;
    private TextView mTvEmpty;
    private FragmentSmsAdapter mAdapter;
    ArrayList<SmsItem> items = new ArrayList<SmsItem>();
    private MainActivity mActivity;
    
    public static FragmentSMS init() {
        FragmentSMS fragment = new FragmentSMS();

        // Supply val input as an argument.
        Bundle args = new Bundle();
        fragment.setArguments(args);

        return fragment;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mActivity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_sms_view, container, false);
        mListView = (ListView) v.findViewById(R.id.listView);
        mTvEmpty = (TextView) v.findViewById(R.id.tvEmpty);
        
        return v;
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        mAdapter = new FragmentSmsAdapter(getActivity(), items);
        mListView.setAdapter(mAdapter);
        
//        Uri allMessage = Uri.parse("content://sms/");
//        
//        MainActivity mainActivity = (MainActivity)getActivity();
//        
//        int[] nDate = mainActivity.getDate();
//        
//        ContentResolver cr = getActivity().getContentResolver();
//        
//        String strDate =  String.format("%s-%s-%s 00:00:00", nDate[0], nDate[1], nDate[2]);
//        String strDate2 =  String.format("%s-%s-%s 23:59:59", nDate[0], nDate[1], nDate[2]);
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date d = null;
//        Date d2 = null;
//        
//        try {
//            d = format.parse(strDate);
//            d2 = format.parse(strDate2);
//        } catch (ParseException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        Long time = d.getTime();
//        Long time2 = d2.getTime();
//        
//        
//        String strSortOrder = CallLog.Calls.DATE + " DESC";
//        String[] whereValues = { "" + time,  "" + time2};
//        String where = "? <= " + CallLog.Calls.DATE + " AND " + CallLog.Calls.DATE + " <= ?";
//        
//        Cursor c = cr.query(allMessage , null , where, whereValues, strSortOrder);
//        
//        int count = 0;
//        
//        ArrayList<SmsItem> items = new ArrayList<SmsItem>();
//        
//        try {
//            if (c != null && c.getCount() > 0){
//                c.moveToFirst();
//    
//                do{
//                    SmsItem item = new SmsItem() ;
//                    
////                    item.setData(c.getString(c.getColumnIndexOrThrow(CallLog.)));
//                    item.setId(c.getString(c.getColumnIndexOrThrow(CallLog.Calls._ID)));
//                    item.setName(c.getString(c.getColumnIndex("body")));
//                    item.setRegDate(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE)));
//                    
//                    items.add(item);
//                    
//                    count++;
//                    
//                } while (c.moveToNext());
//            }
//        } catch ( Exception e ){
//            e.printStackTrace();
//        } finally {
//            if (c != null) {
//                c.close();
//            }
//        }
//        
//        if (items.isEmpty()) {
//            mTvEmpty.setText(mainActivity.getTextViewDate() + " 일자로\n검색된 데이터가 없습니다.");
//        }
    }
    
    @Override
    public ArrayList<Integer> getExistDays(int year, int month) {
        if (month == 0)
            return null;
        
        ArrayList<Integer> arrItems = new ArrayList<Integer>();
        
        ContentResolver cr = getActivity().getContentResolver();
        
        String strDate =  String.format("%s-%s-01 00:00:00", year, month);
        String strDate2 =  String.format("%s-%s-31 23:59:59", year, month);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        Date d2 = null;
        
        try {
            d = format.parse(strDate);
            d2 = format.parse(strDate2);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Long time = d.getTime();
        Long time2 = d2.getTime();
        
        String strSortOrder = CallLog.Calls.DATE + " DESC";
        String[] whereValues = { "" + time,  "" + time2};
        String where = "? <= " + CallLog.Calls.DATE + " AND " + CallLog.Calls.DATE + " <= ?";
        
        Uri allMessage = Uri.parse("content://sms/");
        Cursor c = cr.query(allMessage , null , where, whereValues, strSortOrder);
        
        int count = 0;
        
        try {
            if (c != null && c.getCount() > 0){
                c.moveToFirst();
                do{
                    
                    String retDate = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE));
                    String day = new SimpleDateFormat("dd").format(Long.valueOf(retDate));
                    
                    int nDay = Integer.valueOf(day);
                    if (!arrItems.contains(nDay))
                        arrItems.add(nDay);
                    
                } while (c.moveToNext());
            }
        } catch ( Exception e ){
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        
        Collections.sort(arrItems, new NoAscCompare());
        
        return arrItems;
    }

    @Override
    public void onRefresh(int nYear, int nMonth, int nDay) {

        items = new ArrayList<SmsItem>();
        
        Uri allMessage = Uri.parse("content://sms/");
        
        ContentResolver cr = getActivity().getContentResolver();
        
        String strDate =  String.format("%s-%s-%s 00:00:00", nYear, nMonth, nDay);
        String strDate2 =  String.format("%s-%s-%s 23:59:59", nYear, nMonth, nDay);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        Date d2 = null;
        
        try {
            d = format.parse(strDate);
            d2 = format.parse(strDate2);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Long time = d.getTime();
        Long time2 = d2.getTime();
        
        
        String strSortOrder = CallLog.Calls.DATE + " DESC";
        String[] whereValues = { "" + time,  "" + time2};
        String where = "? <= " + CallLog.Calls.DATE + " AND " + CallLog.Calls.DATE + " <= ?";
        
        Cursor c = cr.query(allMessage , null , where, whereValues, strSortOrder);
        
        int count = 0;
        
        ArrayList<SmsItem> items = new ArrayList<SmsItem>();
        
        try {
            if (c != null && c.getCount() > 0){
                c.moveToFirst();
    
                do{
                    SmsItem item = new SmsItem() ;
                    
//                    item.setData(c.getString(c.getColumnIndexOrThrow(CallLog.)));
                    item.setId(c.getString(c.getColumnIndexOrThrow(CallLog.Calls._ID)));
                    item.setData(c.getString(c.getColumnIndex("body")));
                    item.setRegDate(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE)));
                    item.setType(c.getString(c.getColumnIndex("type")));
                    
                    
                    items.add(item);
                    
                    count++;
                    
                } while (c.moveToNext());
            }
        } catch ( Exception e ){
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        
        mTvEmpty.setVisibility(View.GONE);
        
        if (items.isEmpty()) {
            if (mAdapter.getCount() == 0)
                mTvEmpty.setVisibility(View.VISIBLE);
            return;
        }
            
        mAdapter.setItems(items);
    }

    @Override
    public void onInit() {
        mAdapter.setItems(items);
        mTvEmpty.setVisibility(View.VISIBLE);
    }
    
}
